package models

import (
	"LoveU/utils"
	"crypto/md5"
	"encoding/hex"
	"io"
	"time"

	"math/rand"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

// 采用MD5对字符串加密
func PasswordMD5(password string) string {
	password = password + "00"
	// 使用md5加密
	secret := md5.New()
	secret.Write([]byte(password))
	io.WriteString(secret, password)
	pwd := hex.EncodeToString(secret.Sum(nil))
	return pwd
}

// 检验用户名是否存在
// 返回参数说明
// 400：用户名可用
// utils.REG_NAME_EXISTS：用户名已经存在
func CheckName(name string) int64 {
	o := orm.NewOrm()
	qs := o.QueryTable("user")
	user := new(User)
	err := qs.Filter("name", name).One(user)
	if err == nil {
		return utils.REG_NAME_EXISTS
	}
	return 400
}

// 检验手机号是否已经注册
// 返回参数说明
// 610：手机未被注册
// utils.REG_PHONE_EXISTS：手机已经注册
func CheckPhone(phone string) int64 {
	o := orm.NewOrm()
	qs := o.QueryTable("user")
	user := new(User)
	err := qs.Filter("phone", phone).One(user)
	if err == nil {
		return utils.REG_PHONE_EXISTS
	}
	return 610
}

//将字符串转换成time.Time类型
func String2Time(date string) (time.Time, error) {
	timeLayout := "2006-01-02"                                  //转化所需模板
	loc, _ := time.LoadLocation("UTC")                          //重要：获取时区
	theTime, err := time.ParseInLocation(timeLayout, date, loc) //使用模板在对应时区转化为time.time类型
	beego.Error(theTime)
	return theTime, err
}

func getGentleInt(gentle string) int64 {
	gentleByte := []byte(gentle)
	if len(gentleByte)==0 {
		return 0
	}
	var returns int64
	switch gentleByte[0] {
		case '2': case 'W': case 'w':
			returns = 2
		case '1': case 'M': case 'm':
			returns = 1
		default:
			returns = 0
	}
	return returns
}

// 获取名言
func GetAphorism() *Aphorism {
	o := orm.NewOrm()
	qs := o.QueryTable("aphorism")
	sum, err := qs.Count()
	randnum := rand.Intn(int(sum))
	aphorism := new(Aphorism)
	err = qs.Filter("id", randnum).One(aphorism)
	for err != nil {
		randnum = randnum + 1
		err = qs.Filter("id", randnum).One(aphorism)
	}
	return aphorism
}

// 获取最新版本号
func GetEdition() *Edition {
	o := orm.NewOrm()
	qs := o.QueryTable("edition")
	edition := new(Edition)
	err := qs.OrderBy("-Date").One(edition)
	if err != nil {
		beego.Error(err.Error())
		return nil
	}
	return edition
}
